package dice.sinanya.db.lastMessages;

import dice.sinanya.db.tools.SqliteUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.*;
import java.util.ArrayList;

public class SelectLastMessages {
    private static final Logger logger = LogManager.getLogger(SelectLastMessages.class.getName());
    SqliteUtil sqliteUtil;
    Connection connection;
    int len = 80;

    public SelectLastMessages() {
        sqliteUtil = new SqliteUtil();
        initCon();
        initDb();
    }

    private void initCon() {
        do {
            connection = sqliteUtil.getDiceLogConnection();
        } while (connection == null);
    }

    private void initDb() {
        try (Statement statement = connection.createStatement()) {
            statement.executeUpdate("create table if not exists lastMessages(groupId long,time datetime,PRIMARY KEY (groupId));");
        } catch (SQLException sqlException) {
            logger.error(sqlException.getMessage(), sqlException);
        }
    }

    public ArrayList<Long> selectLastMessages(long leaveTime) {
        ArrayList<Long> groups = new ArrayList<>();
        try {
            if (connection == null || connection.isClosed()) {
                initCon();
            }
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }
        long lastTime =System.currentTimeMillis() - leaveTime * 60 * 60 * 24*1000;
        //language=SQLite
        String sql = "select groupId from lastMessages where time <=?";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setTimestamp(1, new Timestamp(lastTime));
            try (ResultSet resultSet = statement.executeQuery()) {
                while (resultSet.next()) {
                    groups.add(resultSet.getLong("groupId"));
                }
            }
        } catch (SQLException sqlException) {
            logger.error(sqlException.getMessage(), sqlException);
        }
        return groups;
    }
}
